<template>
  <div>
    <div class="query-form">
      <a-form ref="queryFormRef" :model="queryForm" layout="inline" @submit="handleQuery">
        <a-form-item field="userName" label="用户名">
          <a-input v-model="queryForm.userName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item field="mobile" label="联系电话">
          <a-input v-model="queryForm.mobile" placeholder="请输入联系电话" />
        </a-form-item>
        <a-form-item field="state" label="状态">
          <a-select v-model="queryForm.state" placeholder="请选择状态" :style="{width:'150px'}">
            <a-option :value="0" label="停用"></a-option>
            <a-option :value="1" label="启用"></a-option>
          </a-select>
        </a-form-item>
        <a-form-item class="operate">
          <a-button type="primary" html-type="submit">查询</a-button>
          <a-button @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>
    </div>
    <div class="operate-wrapper">
      <a-button type="primary" status="success" @click="openAddModal" v-has:add="'user-add'">添加</a-button>
      <a-button type="primary" status="warning" @click="handlePatchDel">批量删除</a-button>
    </div>
    <a-table
      row-key="_id"
      :data="tableData"
      :row-selection="rowSelection"
      :pagination="paginationProps"
      @page-change="handlePageChange"
      @page-size-change="handleSizeChange"
      @select="handleSelect"
    >
      <template #columns>
        <a-table-column title="用户名" data-index="userName"></a-table-column>
        <a-table-column title="邮箱" data-index="userEmail"></a-table-column>
        <a-table-column title="联系方式" data-index="mobile"></a-table-column>
        <a-table-column title="岗位" data-index="job"></a-table-column>
        <a-table-column title="性别" data-index="sex">
          <template #cell="{ record }">{{ record.sex == 0 ? '男' : '女' }}</template>
        </a-table-column>
        <a-table-column title="状态" data-index="state">
          <template #cell="{ record }">{{ record.state == 0 ? '停用' : '启用' }}</template>
        </a-table-column>
        <a-table-column title="角色" data-index="role">
          <template #cell="{ record }">{{ record.role == 0 ? '系统管理员' : '普通用户' }}</template>
        </a-table-column>
        <a-table-column title="操作">
          <template #cell="{ record }">
            <a-button v-if="record.role != 0" type="text" @click="openUptModal(record)">编辑</a-button>
            <a-button v-if="record.role != 0" type="text" @click="handleDelete(record)">删除</a-button>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <!-- 添加/编辑弹窗 -->
    <a-modal :visible="modalVisible" title="添加/用户" @ok="handleAddOrUpt" @cancel="closeAddModal">
      <a-form ref="modalFormRef" :model="modalForm" :rules="modalFormRules">
        <a-form-item field="userName" label="用户名">
          <a-input v-model="modalForm.userName" />
        </a-form-item>
        <a-form-item field="userEmail" label="邮箱">
          <a-input v-model="modalForm.userEmail" />
        </a-form-item>
        <a-form-item field="mobile" label="联系电话">
          <a-input v-model="modalForm.mobile" />
        </a-form-item>
        <a-form-item field="job" label="职位">
          <a-input v-model="modalForm.job" />
        </a-form-item>
        <a-form-item field="roleList" label="角色">
          <a-select v-model="modalForm.roleList" multiple placeholder="请选择角色">
            <a-option
              v-for="(item,index) in roleListOptions"
              :key="index"
              :value="item._id"
              :label="item.roleName"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="deptList" label="部门">
          <a-select v-model="modalForm.deptList" multiple placeholder="请选择部门">
            <a-option
              v-for="(item,index) in deptListOptions"
              :key="index"
              :value="item._id"
              :label="item.deptName"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="sex" label="性别">
          <a-radio-group v-model="modalForm.sex">
            <a-radio :value="0">男</a-radio>
            <a-radio :value="1">女</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { userAdd, userUpdate, userDelete, userList } from "@/api/user/index.js";
import { roleAllList } from "@/api/role/index.js";
import { deptAllList } from "@/api/dept/index.js";
import { reactive, ref, onMounted } from "vue";
import { Modal } from "@arco-design/web-vue";

export default {
  setup() {
    onMounted(() => {
      getUserList();
      getAllRoleList();
      getAllDeptList();
    });
    // 条件查询表单
    const queryForm = reactive({
      userName: "",
      mobile: "",
      state: 1
    });
    const queryFormRef = ref(null);
    const handleQuery = values => {
      console.log("values", values);
      getUserList();
    };
    const handleReset = () => {
      queryFormRef.value.resetFields();
      getUserList();
    };
    // 添加/编辑用户弹窗
    const modalVisible = ref(false);
    const modalFormRef = ref(null);
    let modalForm = reactive({
      userName: "",
      userEmail: "",
      mobile: "",
      job: "",
      sex: 0,
      roleList: [],
      deptList: []
    });
    const modalFormRules = reactive({
      userName: { required: true, message: "userName is required" },
      userEmail: { required: true, message: "userEmail is required" }
    });
    const action = ref("add");
    const closeAddModal = () => {
      modalVisible.value = false;
      modalFormRef.value.resetFields();
    };
    // 所有角色列表
    const roleListOptions = ref([]);
    const getAllRoleList = async () => {
      const { data } = await roleAllList();
      roleListOptions.value = data.data;
    };

    // 所有部门列表
    const deptListOptions = ref([]);
    const getAllDeptList = async () => {
      const { data } = await deptAllList();
      deptListOptions.value = data.data;
    };

    // 添加
    const openAddModal = () => {
      action.value = "add";
      modalFormRef.value.resetFields();
      modalVisible.value = true;
    };
    // 更新
    const openUptModal = record => {
      action.value = "upt";
      Object.assign(modalForm, record);
      modalVisible.value = true;
    };
    const handleAddOrUpt = () => {
      modalFormRef.value.validate(async (errors, Record) => {
        if (errors) return;
        if (action.value == "add") {
          const { data } = await userAdd(modalForm);
          console.log("data", data);
        }
        if (action.value == "upt") {
          const { data } = await userUpdate(modalForm);
          console.log("data", data);
        }
        getUserList();
        modalVisible.value = false;
      });
    };
    // 复选框
    const _ids = ref([]);
    const rowSelection = reactive({
      type: "checkbox",
      showCheckedAll: true
    });
    const handleSelect = rowKeys => {
      console.log(rowKeys);
      _ids.value = rowKeys;
    };
    // 表格数据
    let tableData = ref([]);
    const pager = reactive({
      pageNum: 1,
      pageSize: 10
    });
    const getUserList = async () => {
      let params = { ...queryForm, ...pager };
      const { data } = await userList(params);
      tableData.value = data.data.list;
      paginationProps.total = data.data.page.total;
    };
    // 分页
    const paginationProps = reactive({
      total: 0,
      current: 1,
      pageSize: 10,
      showTotal: true,
      showPageSize: true
    });
    const handlePageChange = val => {
      paginationProps.current = val;
      pager.pageNum = val;
      getUserList();
    };
    const handleSizeChange = val => {
      paginationProps.pageSize = val;
      pager.pageSize = val;
      getUserList();
    };
    // 批量删除
    const handlePatchDel = () => {
      Modal.warning({
        title: "警告",
        content: "此操作将停用该用户，是否继续！",
        hideCancel: false,
        onOk: async () => {
          const { data } = await userDelete({
            _ids: _ids.value
          });
          console.log(data);
          getUserList();
        }
      });
    };

    // 删除
    const handleDelete = record => {
      Modal.warning({
        title: "警告",
        content: "此操作将停用该用户，是否继续！",
        hideCancel: false,
        onOk: async () => {
          const { data } = await userDelete({
            _ids: [record._id]
          });
          console.log(data);
          getUserList();
        }
      });
    };
    return {
      queryForm,
      handleReset,
      queryFormRef,
      modalVisible,
      modalForm,
      getAllRoleList,
      roleListOptions,
      deptListOptions,
      getAllDeptList,
      action,
      modalFormRules,
      rowSelection,
      handleSelect,
      tableData,
      pager,
      paginationProps,
      handlePageChange,
      handleSizeChange,
      getUserList,
      handleQuery,
      openAddModal,
      closeAddModal,
      handleAddOrUpt,
      modalFormRef,
      handlePatchDel,
      openUptModal,
      handleDelete
    };
  }
};
</script>

<style lang="scss" scoped>
</style>